//
//  PaperViewModel.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/9.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa

class PaperViewModel {
    
    //RX 垃圾回收袋
    var disposeBag = DisposeBag()
    
    ///试卷id
    var paperId: Int
    ///试卷状态
    var status: PaperStatus
    
    ///试卷标题
    var title: String?
    ///模式
//    var method: PaperMethod
    ///错题事件详情需要
    var pUserSummaryId: Int?
    
    ///当前页面，从0开始
    var index = Variable(0)
    
    public var vmData :Variable<PaperModel>
    ///试卷
    var paper: PaperModel? {
        set {
            if newValue != nil {
                vmData.value = newValue!
            }
        }
        get {
            return vmData.value
        }
    }
    
    ///试卷列表请求（试用列表，全部列表）
    var paperListCommand = PublishSubject<PaperStatus>()
    ///收藏请求
    var likeCommand = PublishSubject<(PaperItemModel, Int)>()
    
    
    init(_ paperId: Int,
         paper: PaperModel? = nil,
         status: PaperStatus,
         pUserSummaryId: Int? = nil,
         title: String? = nil) {
        if paper != nil {
            self.vmData = Variable(paper!)
        }
        else {
            self.vmData = Variable(PaperModel.init())
        }
        self.paperId = paperId
        self.status = status
        self.paperId = paperId
        self.pUserSummaryId = pUserSummaryId
        self.title = title
        
        self.initCommand()
    }
    
    private func initCommand() {
    
        ///获取试卷详情
        paperListCommand.subscribe(onNext: { [weak self] (status) in
            switch status {
            case .bought, .free:
                self?.loadItems()
            case .trial:
                self?.loadTrial()
            case .likes:
                self?.loadLikes()
            case .errorItems:
                self?.loadErrors()
            case .record:
                self?.loadRecordDetial()
            default:
                break
            }
        }).disposed(by: disposeBag)
        
        //收藏
        likeCommand.subscribe(onNext: { [weak self] (item, isLike) in
            self?.like(item: item, isLike: isLike)
        }).disposed(by: disposeBag)
    }
    
    ///重考
    func reEaxm() {
        status = .bought
        paperListCommand.onNext(status)
    }
    
    
    ///提交试卷
    func submit(_ complete: ((PaperModel?)->Void)?) {
        guard let pUserSummaryId = paper?.pUserSummaryId else { return }
        
        guard let itemAnswers = fomatUserAnwer() else { return }
//        if itemAnswers.count < 1 {
//            lsf_alert("试卷答案不能为空")
//            return;
//        }
    
        startAnimating()
        paperProvider.rx
            .request(.submit(pUserSummaryId: pUserSummaryId, itemsAnswers: itemAnswers))
            .asObservable()
            .mapRespnseToObject(type: PaperModel.self)
            .subscribe(onNext: { [weak self] (result) in
                let resultPaper = self?.paper?.updateFromResultPaper(result)
                resultPaper?.title = self?.title
                complete?(resultPaper)
                }, onError: { (error) in
                    stopAnimating()
                    showError(error)
                    complete?(nil)
            }, onCompleted: {
                stopAnimating()
            }).disposed(by: disposeBag)
    }
    
    ///提交自评分
    public func selfReport(_ complete: VoidBlock?)  {
        guard let pUserSummaryId = paper?.pUserSummaryId else { return }
        
        guard let userScore = fomatUserScore() else { return }
        startAnimating()
        paperProvider.rx
            .request(.selfReportScore(pUserSummaryId: pUserSummaryId, itemsScore: userScore))
            .asObservable()
            .mapRespnseJson()
            .subscribe(onError: { (error) in
            stopAnimating()
            showError(error)
        }, onCompleted: {
            stopAnimating()
            ///自评分提交成功，计算分数
            complete?()
        }).disposed(by: disposeBag)
    }
}

// MARK:-
// MARK: 网络请求
extension PaperViewModel {
    
    
    ///获取所有试题
    private func loadItems() {
        loadList(.allItems(paperId: paperId))
        
    }
    
    ///获取试用试卷
    private func loadTrial() {
        loadList(.trial(paperId: paperId))
    }
    
    ///获取收藏试卷试题
    private func loadLikes() {
        loadList(.likesItemList(paperId: paperId))
    }
    
    ///获取错题
    private func loadErrors() {
        guard let pUserSummaryId = self.pUserSummaryId else { return }
        loadList(.errorListItems(paperId: paperId, pUserSummaryId: pUserSummaryId))
    }
    
    ///获取错题
    private func loadRecordDetial() {
        guard let pUserSummaryId = self.pUserSummaryId else { return }
        loadList(.recordDetail(pUserSummaryId: pUserSummaryId))
    }
    
    ///试卷列表
    private func loadList(_ api: PaperAPI) {
        startAnimating()
        paperProvider.rx
            .request(api)
            .asObservable()
            .mapRespnseToObject(type: PaperModel.self)
            .subscribe(onNext: { [weak self] (paper) in
                
                guard let strongSelf = self else { return }
                
                strongSelf.paper = paper
            
                paper.updatePaperItemMethod(strongSelf.status)
                strongSelf.paper?.paperId = strongSelf.paperId
    
            }, onError: { (error) in
                    stopAnimating()
                    showError(error)
            }, onCompleted: {
                stopAnimating()
            }).disposed(by: disposeBag)
    }
    
    //收藏
    private func like(item: PaperItemModel, isLike: Int) {
        startAnimating()
        paperProvider.rx
            .request(.likes(paperId: paperId, itemId: item.id!, action: isLike))
            .asObservable()
            .mapRespnseJson()
            .subscribe(onNext: { (data) in
                if isLike == 1 {
                    item.userLike = .like
                }
                else {
                    item.userLike = .default
                }
                
            }, onError: { (error) in
                stopAnimating()
                showError(error)
            }, onCompleted: {
                if isLike == 1 {
                    lsf_alert("收藏成功")
                }
                else {
                    lsf_alert("取消收藏")
                }
                
                stopAnimating()
            }).disposed(by: disposeBag)
    }

    
 
}

extension PaperViewModel {
    ///将用户答案封装成Json字符串
    private func fomatUserAnwer() -> [[String: Any]]? {
        var itemsAnswers = [[String: Any]]()
        guard let paperItems = paper?.paperItems else { return nil }
        for item in paperItems {
            
            if let answer = item.userAnswer,
                String.lsf_hasValue(answer) {
                
                let answerDic = ["itemId" : item.id!,
                           "answer": answer] as [String : Any]
                itemsAnswers.append(answerDic)
            }
        }
        
        return itemsAnswers
    }
    
    
    private func fomatUserScore() -> [[String: Any]]? {
        var userScoreItems = [[String: Any]]()
        guard let paperItems = paper?.paperItems else {
            return nil
        }
        
        for item in paperItems {
            if let userScore = item.userScore {
                let dic: [String : Any] = ["itemId": item.id!,
                                           "selfReportedScore": userScore]
                userScoreItems.append(dic)
            }
        }
        return userScoreItems
    }

}
